import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/components/enter_store_button.dart';
import 'package:mall/components/image_network.dart';
import 'package:mall/core/models/store_product_query.dart';
import 'package:mall/core/models/store_search.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/screens/product/product_page.dart';
import 'package:mall/screens/store/store_screen.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../theme.dart';

/// 发现店铺（店铺搜索）
class HomeStoreScreen extends StatefulWidget {
  static const routeName = "/HomeStoreScreen";
  @override
  _HomeStoreScreenState createState() => _HomeStoreScreenState();
}

class _HomeStoreScreenState extends State<HomeStoreScreen> {
  String _keyword;
  RefreshController _refreshController;
  int _pageIndex;
  StoreSearch _storeSearch;
  final List<Store> _list = [];

  @override
  void initState() {
    super.initState();
    _refreshController = RefreshController(initialRefresh: true);
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("发现店铺"),
      ),
      body: Column(
        children: [
          if (_storeSearch != null) buildSearchField(),
          SizedBox(height: 8.w),
          Expanded(
            child: SmartRefresher(
              controller: _refreshController,
              enablePullUp: _storeSearch != null && _storeSearch.models.content.length == 10,
              onRefresh: _onRefresh,
              onLoading: _onLoading,
              child: Wrap(
                alignment: WrapAlignment.center,
                spacing: 8.w,
                runSpacing: 8.w,
                children: List.generate(_list.length, (index) => _buildStoreItem(_list[index])),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Container buildSearchField() {
    final outlineInputBorder = OutlineInputBorder(
      borderSide: BorderSide(color: kLineColor),
      borderRadius: BorderRadius.circular(15.w),
    );
    return Container(
      margin: EdgeInsets.all(8.w),
      height: 30.w,
      child: TextField(
        decoration: InputDecoration(
          contentPadding: EdgeInsets.symmetric(horizontal: 24.w),
          focusedBorder: outlineInputBorder,
          enabledBorder: outlineInputBorder,
          border: outlineInputBorder,
        ),
        textInputAction: TextInputAction.search,
        onSubmitted: _search,
      ),
    );
  }

  void _search(String text) {
    _keyword = text;
    _refreshController.requestRefresh();
  }

  Widget _buildStoreItem(Store store) {
    return GestureDetector(
      onTap: () => _onTapStoreItem(store),
      child: Container(
        padding: EdgeInsets.all(8.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(4.w),
        ),
        width: (375.0 - 8 * 2).w,
        child: Column(
          children: [
            Row(
              children: [
                ImageNetwork(url: "${store.logoUrl}", width: 25.w, height: 25.w),
                SizedBox(width: 8.w),
                Text("${store.name}"),
                Spacer(),
                EnterStoreButton(),
              ],
            ),
            SizedBox(height: 8.w),
            Row(
              children: [
                SizedBox(width: (25 + 8).w),
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 4.w),
                  decoration: BoxDecoration(
                    color: Color(0xFFFCAC48),
                    borderRadius: BorderRadius.circular(10.w),
                  ),
                  child: Text(
                    "${store.storeTypeText}",
                    style: TextStyle(color: Colors.white, fontSize: 10.w),
                  ),
                ),
                SizedBox(width: 8.w),
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 4.w),
                  decoration: BoxDecoration(
                    color: Color(0xFF298CF6),
                    borderRadius: BorderRadius.circular(10.w),
                  ),
                  child: Text(
                    "业",
                    style: TextStyle(color: Colors.white, fontSize: 10.w),
                  ),
                ),
                SizedBox(width: 8.w),
                Text(
                  "${store.levelText}",
                  style: TextStyle(fontSize: 10.w),
                )
              ],
            ),
            SizedBox(height: 8.w),
            Wrap(
              spacing: 8.w,
              runSpacing: 8.w,
              children: List.generate(
                store.topProducts.length,
                (index) => _buildItem(store.topProducts[index]),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _onTapStoreItem(Store store) {
    Navigator.of(context).pushNamed(StoreScreen.routeName, arguments: store.id);
  }

  Widget _buildItem(Product product) {
    return GestureDetector(
      onTap: () => _onTapItem(product),
      child: Container(
        decoration: BoxDecoration(
          border: Border.all(color: kLineColor),
          borderRadius: BorderRadius.circular(4.w),
        ),
        width: ((375.0 - 8 * 5) / 2).w,
        height: ((375.0 - 8 * 5) / 2).w,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(4.w),
          child: ImageNetwork(url: "${product.productImage}"),
        ),
      ),
    );
  }

  void _onTapItem(Product product) {
    Navigator.of(context).pushNamed(
      ProductPage.routeName,
      arguments: ProductPageArgs(null, product.productId, product.miaId, product.curStoreId),
    );
  }

  /// 第一页
  void _onRefresh() async {
    _pageIndex = 0;
    final api = context.read<Api>();
    try {
      final storeSearch = await api.storeSearch(_keyword, _pageIndex);
      if (!mounted) {
        return;
      }
      _refreshController.refreshCompleted();
      setState(() {
        _storeSearch = storeSearch;
        _list.clear();
        _list.addAll(storeSearch.models.content);
      });
    } on DioError catch (e) {
      _refreshController.refreshFailed();
      debugPrint("${e.message}");
      EasyLoading.showToast("${e.message}");
    }
  }

  /// 更多页
  void _onLoading() async {
    _pageIndex++;
    final api = context.read<Api>();
    try {
      final storeSearch = await api.storeSearch(_keyword, _pageIndex);
      if (!mounted) {
        return;
      }
      _refreshController.loadComplete();
      setState(() {
        _storeSearch = storeSearch;
        _list.addAll(storeSearch.models.content);
      });
    } on DioError catch (e) {
      _refreshController.loadFailed();
      debugPrint("${e.message}");
      EasyLoading.showToast("${e.message}");
    }
  }
}
